package cn.com.shopec.erp.purchase.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.base.entity.SupplierInfo;
import cn.com.shopec.erp.base.service.impl.SupplierInfoService;
import cn.com.shopec.erp.base.vo.SupplierVo;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.financing.entity.WhareHouse;
import cn.com.shopec.erp.financing.service.IWhareHouseServer;
import cn.com.shopec.erp.product.entity.Product;
import cn.com.shopec.erp.product.service.IProdSupplierService;
import cn.com.shopec.erp.product.service.IProductService;
import cn.com.shopec.erp.product.vo.ProdSupplierVo;
import cn.com.shopec.erp.product.vo.ProductVo1;
import cn.com.shopec.erp.purchase.commo.PRPropertyUtils;
import cn.com.shopec.erp.purchase.model.PoProductInfo;
import cn.com.shopec.erp.purchase.service.IPurchaseOrderService;
import cn.com.shopec.erp.purchase.service.IPurchaseRequisitionService;
import cn.com.shopec.erp.purchase.vo.PurchaseOrderVo;
import cn.com.shopec.erp.purchase.vo.PurchaseRequisitionProductVo;
import cn.com.shopec.erp.stock.commo.StockInUtil;
import cn.com.shopec.erp.stock.vo.StockInProductVo;
import cn.com.shopec.erp.stock.vo.StockInVo;
import cn.com.shopec.erp.system.common.UserUtils;
import cn.com.shopec.erp.system.service.IUserService;
import cn.com.shopec.erp.system.vo.RoleVo;

/**
 * @ClassName: PurchaseOrderController
 * @Description: 采购管理-采购单Controller
 * @author: Liang shun wang
 * @date 2016-11-25 下午2:10:32
 * 
 */
@Controller
@RequestMapping("/manager/purchase/orders")
public class PurchaseOrderController {

	private static final Log log = LogFactory.getLog(PurchaseOrderController.class);

	@Resource
	private IPurchaseOrderService poService;

	@Resource
	private IWhareHouseServer iWhareHouseServer;

	@Resource
	private PRPropertyUtils prUtils;

	@Resource
	private IProductService productService;

	@Resource
	private IProdSupplierService prodSupplierService;

	@Resource
	private IPurchaseRequisitionService purchaseRequisitionService;

	@Resource
	private SupplierInfoService supplierInfoService;

	@Resource
	private IPurchaseRequisitionService purchaseReuistion;
	
	@Resource
	private IUserService userService;

	/**
	 * @Title: purchaseOrderList
	 * @Description: 至采购单管理列表页面
	 * @param poQueryVo
	 * @param modelMap
	 * @return
	 * @throws Exception
	 * @throws @author:
	 *             Liang shun wang
	 * @date: 2013-5-25下午5:25:59
	 */
	@RequestMapping("poList")
	public ModelAndView purchaseOrderList(PurchaseOrderVo purchaseOrderVo, ModelMap modelMap) throws Exception {
		List<RoleVo> roleVos = this.userService.getOwnRoleVos(UserUtils.getUserVo());
		modelMap.put("roleVos", roleVos);
		modelMap.put("purchaseOrderVo", purchaseOrderVo);
		return new ModelAndView("purchase/orders/po_list");
	}

	/**
	 * @Title: ajaxToPurchaseOrderList
	 * @Description: 得到采购单列表，以json形式返回
	 * @param poQueryVo
	 * @param pageQuery
	 * @param modelMap
	 * @return
	 * @throws Exception
	 * @throws @author:
	 *             Liang Shun Wang
	 * @date: 2013-5-25下午5:26:19
	 */
	@RequestMapping("ajaxToPoList")
	@ResponseBody
	public String ajaxToPurchaseOrderList(PurchaseOrderVo purchaseOrderVo, PageQuery pageQuery, ModelMap modelMap)
			throws Exception {
		PageFinder<PurchaseOrderVo> pagedBrandList = this.poService.getPagedPurchaseOrderList(purchaseOrderVo,pageQuery);
		modelMap.put("Rows", pagedBrandList.getData());
		modelMap.put("Total", pagedBrandList.getRowCount());
		return JsonHelper2.toJson(modelMap);
	}

	/**
	 * @methodName：addRequisition
	 * @Description: 进入添加采购单页面
	 * @param
	 * @return String
	 * @author: liang shun wang
	 * @throws Exception
	 * @date: 2013-5-21 下午19:10:03
	 */
	@RequestMapping("/to_add_purchase")
	public ModelAndView addPurchase(String productlist, PurchaseOrderVo prv, PageQuery pageQuery, ModelMap model)
			throws Exception {
		model.put("prv", prv);
		List<WhareHouse> house = this.iWhareHouseServer.getAllWhareHouse();
		model.put("house", JsonHelper2.toJson(house));
		model.put("supplierInfo", supplierInfoService.getPagedCollectSetList(pageQuery).getData());
		return new ModelAndView("purchase/orders/create_requisition", model);
	}

	/**
	 * @methodName：addToRequisition
	 * @Description: 创建采购单
	 * @param
	 * @return String
	 * @author: liang shun wang
	 * @date: 2013-5-22 下午15:10:03
	 */
	@RequestMapping("/add_purchase")
	@ResponseBody
	public String addToRequisition(String productlist, PurchaseOrderVo purchaseOrderVo, ModelMap model) throws IOException {
		if (purchaseOrderVo != null) {
			if (productlist != null) {
				List<PurchaseRequisitionProductVo> prpvlist = this.prUtils.getStringToProduct(productlist, false);
				purchaseOrderVo.setPrplist(prpvlist);
				for (PurchaseRequisitionProductVo element : prpvlist) {
					if (element != null) {
						Product product = productService.getProductIntfoByCommon(element.getCommodityNo());
						WhareHouse whare = iWhareHouseServer.getWhareHouseByNo(element.getPpWarehouseNo());
						if (product.getInventoryType() != whare.getWhType()) {
							return SZSCMConstant.WHARE_HOUSE;
						} else {
							purchaseOrderVo.setCreatePerson(UserUtils.getLoginUserName());
							purchaseOrderVo.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
							return poService.addPurchaseRequisitionVo(purchaseOrderVo);
						}
					}

				}

			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * @Title: updateBrand
	 * @Description: 修改采购单信息
	 * @param brandVo
	 * @param map
	 * @return
	 * @throws @author:
	 *             LiangShunWang
	 * @date: 2013-5-27下午02:48:51
	 */
	@RequestMapping("/update_purchase")
	@ResponseBody
	public String updateDefective(PurchaseOrderVo purchaseOrderVo, ModelMap map, HttpServletRequest request,
			HttpServletResponse response,String poNo) {
		String result = SZSCMConstant.FAIL;
		try {
			String productlist = request.getParameter("productlist");
			if (productlist != null && !productlist.equals("")) {
				List<PurchaseRequisitionProductVo> prpvlist = this.prUtils.getStringToProduct(productlist, false);
				if (this.purchaseReuistion.updatePurchaseOrder(prpvlist, poNo)) {
					result = SZSCMConstant.SUCCESS;
				}
			}
		} catch (Exception e) {
			log.error("update_purchase:" + e.getMessage(), e);
		}
		return result;
	}

	/**
	 * @Title: deletePurchase
	 * @Description: 删除采购单信息
	 * @param brandVo
	 * @param map
	 * @return
	 * @throws Exception
	 * @throws @author:LiangShunWang
	 * @date: 2016-11-21下午19:16:58
	 */
	@RequestMapping("to_delete_purchase")
	@ResponseBody
	public String deletePurchase(PurchaseOrderVo purchaseOrderVo) {
		try {
			this.poService.deletePurchase(purchaseOrderVo.getId());
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("deleteBrand:" + e.getMessage(), e);
			return SZSCMConstant.FAIL;
		}
	}

	/**
	 * @Title: deletePurchase
	 * @Description: 采购
	 * @param brandVo
	 * @param map
	 * @return
	 * @throws Exception
	 * @throws @author:LiangShunWang
	 * @date: 2016-11-21下午19:16:58
	 */
	@RequestMapping("to_good_purchase")
	@ResponseBody
	public String purchaseList(PurchaseOrderVo purchaseOrderVo) {
		try {
			this.poService.purchaseOrderList(purchaseOrderVo.getId());
			return SZSCMConstant.SUCCESS;
		} catch (Exception e) {
			log.error("deleteBrand:" + e.getMessage(), e);
			return SZSCMConstant.FAIL;
		}
	}

	/**
	 * @methodName：getCommodityList
	 * @Description: 进入选择商品页面
	 * @param ProductVo pageQuery
	 * @return
	 * @author: Liang Shun Wang
	 * @throws Exception
	 * @date: 2013-5-22 下午15:10:03
	 */
	@RequestMapping("getCommodityList")
	public ModelAndView getCommodityList(ProductVo1 productVo, PageQuery pageQuery, ModelMap model) throws Exception {
		model.put("productVo", productVo);
		return new ModelAndView("purchase/product_elect", model);
	}

	/**
	 * @methodName：getAjaxCommodityList
	 * @Description: 获取商品
	 * @param ProductVo pageQuery
	 * @return
	 * @author: Liang Shun Wang
	 * @throws Exception
	 * @date: 2013-5-22 下午15:10:03
	 */
	/*
	 * @RequestMapping("getAjaxCommodityList")
	 * 
	 * @ResponseBody public String getAjaxCommodityList(ProductVo1 productVo,
	 * PageQuery pageQuery) throws Exception { PageFinder<ProductVo1>
	 * productVoList =
	 * this.productService.getPagedProductListByProduct(productVo, pageQuery);
	 * ModelMap map = new ModelMap(); map.put("Rows", productVoList.getData());
	 * map.put("Total", productVoList.getRowCount()); return
	 * JsonHelper2.toJson(map); }
	 */
	@RequestMapping("getAjaxCommodityList")
	@ResponseBody
	public String getAjaxCommodityList(ProductVo1 productVo, PageQuery pageQuery) throws Exception {
		PageFinder<ProductVo1> productVoList = this.productService.getPagedProductListProduct(productVo, pageQuery);
		ModelMap map = new ModelMap();
		map.put("Rows", productVoList.getData());
		map.put("Total", productVoList.getRowCount());
		return JsonHelper2.toJson(map);
	}

	/**
	 * 分页查询供应商页面跳转
	 * 
	 * @param supplierInfo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("pageFinderSupplier")
	public String pageFinderSupplier(ProdSupplierVo prodSupplierVo, ModelMap map) {
		map.put("prodSupplierVo", prodSupplierVo);
		return "/purchase/dialog";
	}

	/**
	 * 分页查询供应商
	 * 
	 * @param supplierInfo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("/getAjaxPageFinderProdSupplier")
	@ResponseBody
	public String getAjaxPageFinderProdSupplier(ProdSupplierVo prodSupplierVo, PageQuery pageQuery, ModelMap map) {
		if (StringUtil.isExist(prodSupplierVo.getProdNo())) {
			prodSupplierVo.setProdNo(prodSupplierVo.getProdNo().replace("'", ""));
		}
		PageFinder<ProdSupplierVo> ProdSupplierVos = this.prodSupplierService.getPageFinderProdSupplier(prodSupplierVo,
				pageQuery);
		map.put("Rows", ProdSupplierVos.getData());
		map.put("Total", ProdSupplierVos.getRowCount());
		return JsonHelper2.toJson(map);
	}

	/**
	 * @Title: showPoDetail
	 * @Description: 展现采购单详情
	 * @param poNo
	 * @return
	 * @throws Exception
	 * @throws @author: liang shun wang
	 * @date: 2013-5-27下午2:33:39
	 */
	@RequestMapping("showPoDetail")
	public ModelAndView showPoDetail(String poNo, String num, String showList, ModelMap modelMap) throws Exception {
		/*
		 * PurchaseOrderDetail po = this.poService.getPurchaseOrderDetail(poNo);
		 * modelMap.put("po", po); modelMap.put("num", num);
		 */
		PurchaseOrderVo po = this.poService.getPurchaseOrder(poNo);
		modelMap.put("po", po);
		modelMap.put("num", num);

		/*
		 * boolean isModifiable = this.poService.isModifiablePo(po);
		 * //先由service判断该采购单是否可以修改 //isModifiable = isModifiable &&
		 * UserUtils.isPurchaseMan() && num.equals("1");
		 * //另外再加上3个条件：当前用户是采购员，且采购单是当前用户创建的,且是点修改过来的 isModifiable =
		 * isModifiable && UserUtils.isPurchaseMan() && num.equals("1");
		 * modelMap.put("isModifiable", isModifiable);
		 */
		modelMap.put("showList", StringUtil.isBlank(showList) ? "prods" : showList);
		return new ModelAndView("purchase/orders/po_detail");
	}

	/**
	 * @Title: showPoDetail
	 * @Description: 展现采购单详情
	 * @param poNo
	 * @return
	 * @throws Exception
	 * @throws @author:liang shun wang
	 * @date: 2013-5-27下午2:33:39
	 */
	@RequestMapping("showPoDetail_Update")
	public ModelAndView showPoDetailUpdate(String poNo, String num, String showList, ModelMap modelMap)
			throws Exception {
		/*
		 * PurchaseOrderDetail po = this.poService.getPurchaseOrderDetail(poNo);
		 * modelMap.put("po", po); modelMap.put("num", num);
		 */
		PurchaseOrderVo po = this.poService.getPurchaseOrder(poNo);
		modelMap.put("po", po);
		modelMap.put("num", num);
		/*
		 * boolean isModifiable = this.poService.isModifiablePo(po);
		 * //先由service判断该采购单是否可以修改 //isModifiable = isModifiable &&
		 * UserUtils.isPurchaseMan() && num.equals("1");
		 * //另外再加上3个条件：当前用户是采购员，且采购单是当前用户创建的,且是点修改过来的 isModifiable =
		 * isModifiable && UserUtils.isPurchaseMan() && num.equals("1");
		 * modelMap.put("isModifiable", isModifiable);
		 */
		modelMap.put("showList", StringUtil.isBlank(showList) ? "prods" : showList);
		return new ModelAndView("purchase/orders/modify");
	}

	/**
	 * @Title: toUpdateBrand
	 * @Description: 跳转到修改采购单页面
	 * @param brandVo
	 * @param modelMap
	 * @return
	 *  @author: LiangShunWang
	 * @date: 2013-5-27下午02:43:02
	 */
	@RequestMapping("/to_update_purchase")
	public String toUpdateDefective(String poNo, ModelMap map) {
		try {
			PurchaseOrderVo purchase = this.poService.getPurchaseOrder(poNo);
			map.put("purchase", purchase);
		} catch (Exception e) {
			log.error("toUpdateBrand:" + e.getMessage(), e);
		}
		return "/purchase/orders/po_detail";
	}

	/**
	 * @Title: ajaxToPoProductList
	 * @Description: 根据采购单号，取得采购单的货品信息，以json方式返回
	 * @param poNo
	 * @param pageQuery
	 * @param modelMap
	 * @return
	 * @throws Exception
	 * @throws @author:liang shun wang
	 * @date: 2013-5-27下午3:14:28
	 */
	@RequestMapping("ajaxToPoProductList")
	@ResponseBody
	public String ajaxToPoProductList(String poNo, PageQuery pageQuery, ModelMap modelMap) throws Exception {
		JSONObject jsonObj = new JSONObject();
		// PageFinder<PoProductInfo> pageFinder =
		// this.poService.getPagedPoProducts(poNo, pageQuery);
		PageFinder<PurchaseRequisitionProductVo> pageFinder = this.poService.getPagedPoProducts2(poNo, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * @Title: toPoAudit
	 * @Description: 至采购单审核页面
	 * @param poAudit
	 * @param modelMap
	 * @return
	 * @throws Exception
	 * @throws @author: liang shun wang
	 * @date: 2013-5-27上午11:19:17
	 */
	@RequestMapping("toPoAudit")
	public ModelAndView toPoAudit(String poNo, ModelMap modelMap) throws Exception {
		try {
			PurchaseOrderVo purchase = this.poService.getPurchaseOrder(poNo);
			modelMap.put("purchase", purchase);
		} catch (Exception e) {
			log.error("toUpdateBrand:" + e.getMessage(), e);
		}
		return new ModelAndView("purchase/orders/po_audit");
	}

	@RequestMapping("/poAudit")
	@ResponseBody
	public String poAudit(PurchaseOrderVo purchaseOrderVo, ModelMap map, String tabId) {
		try {
			this.poService.updatePurchaseOrderByAudit(purchaseOrderVo);
		} catch (Exception e) {
			log.error("update_purchase:" + e.getMessage(), e);
			return SZSCMConstant.FAIL;
		}
		return SZSCMConstant.SUCCESS;
	}

	/**
	 * @Title: toPoProdPriceAndQuantityModify
	 * @Description: 至采购单商品价格及数量修改页面
	 * @param poNo
	 * @param prodNo
	 * @param modelMap
	 * @return
	 * @throws Exception
	 * @throws @author:liang shun wang
	 * @date: 2013-5-27下午5:40:47
	 */
	@RequestMapping("toPoProdPriceAndQuantityModify")
	public ModelAndView toPoProdPriceAndQuantityModify(String poNo, String prodNo, ModelMap modelMap) throws Exception {
		PoProductInfo poProd = this.poService.getPoProduct(poNo, prodNo);
		modelMap.put("poProduct", poProd);
		return new ModelAndView("purchase/orders/po_detail");
	}

	/**
	 * @Title: poProdPriceAndQuantityModify
	 * @Description: 修改采购货品价格和数量
	 * @param poProd
	 * @return
	 * @throws Exception
	 * @throws @author: liang shun wang
	 * @date: 2013-5-27下午7:15:16
	 */
	@RequestMapping("poProdPriceAndQuantityModify")
	@ResponseBody
	public String poProdPriceAndQuantityModify(PoProductInfo poProd) throws Exception {
		String resMsg = SZSCMConstant.FAIL;
		try {
			// 判断是否是该采购员自己的采购单
			/*
			 * PurchaseOrderInfo poInfo =
			 * this.poService.getPurchaseOrderInfo(poProd.getPoNo());
			 * if(!UserUtils.getLoginUserName().equals(poInfo.getCreatePerson())
			 * ) { resMsg = "操作失败，采购员只能修改自己创建的采购单";
			 * 
			 * } else {
			 */
			// 更新采购货品的价格和数量
			int res = this.poService.updatePoProductPriceAndQuantity(poProd.getPoNo(), poProd.getProdNo(),
					poProd.getPurUnitPrice(), poProd.getPurQuantity());

			switch (res) {
			case SZSCMConstant.SUCCESS_INT:
				resMsg = SZSCMConstant.SUCCESS;
				break;
			case -1:
				resMsg = "操作失败，采购单编号不正确";
				break;
			case -2:
				resMsg = "操作失败，该采购单当前不可修改";
				break;
			case -3:
				resMsg = "操作失败，采购单编号或货品编号不正确";
				break;
			default:
				;
			}
			// }

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return resMsg;
	}

	/**
	 * toAddStockInForPurchase
	 * 
	 * @Description:跳转入库
	 * @param poProd
	 * @return
	 * @throws Exception
	 * @throws @author:liang shun wang
	 * @date: 2016-12-1下午7:15:16
	 */
	@RequestMapping("/AddStockInForPurchase")
	public String toAddStockInForPurchase(String tabId, String poNo, PageQuery pageQuery, ModelMap map)
			throws Exception {
		PageFinder<PurchaseOrderVo> purchase = poService.getPurchaseOrderById(poNo, pageQuery);
		purchase.getData().get(0);
		StockInVo stockIn = StockInUtil.parseStockVo(purchase.getData().get(0));
		map.put("tabId", tabId);
		map.put("stockIn", stockIn);
		map.put("stockInViewType", SZSCMConstant.STOCK_PUR_IN_VIEW);
		return "/stock/stockIn_detail";
	}

	/**
	 * @Title:PurchaseOrderListToWarehouse
	 * @Description:查询入库所需的参数
	 * @param poProd
	 * @return
	 * @throws Exception
	 * @throws @author:liang shun wang
	 * @date: 2016-12-1下午7:15:16
	 */
	@RequestMapping("/purchaseOrderList_ToWarehouse")
	@ResponseBody
	public String purchaseOrderListToWarehouse(PurchaseRequisitionProductVo purchaseRequisitionProductVo,
			PageQuery pageQuery, ModelMap modelMap) throws Exception {
		PageFinder<PurchaseRequisitionProductVo> pagedBrandList = this.purchaseRequisitionService
				.purchaseOrderListToWarehouse(purchaseRequisitionProductVo, pageQuery);
		List<StockInProductVo> stockInProduct = StockInUtil.parseStockInProductVo(pagedBrandList.getData());
		modelMap.put("Rows", stockInProduct);
		modelMap.put("Total", pagedBrandList.getRowCount());
		return JsonHelper2.toJson(modelMap);
	}

	/**
	 * @methodName：getCommodityList
	 * @Description: 进入选择供应商页面
	 * @param ProductVo pageQuery
	 * @return
	 * @author: liang shun wang
	 * @throws Exception
	 * @date: 2013-5-22 下午15:10:03
	 */
	@RequestMapping("getSupplierInfoList")
	public ModelAndView getSupplierInfoList(ProductVo1 productVo, PageQuery pageQuery, ModelMap model)
			throws Exception {
		model.put("productVo", productVo);
		return new ModelAndView("purchase/orders/supplierInfo_elect", model);
	}

	/**
	 * @methodName：getAjaxCommodityList
	 * @Description: 获取供应商
	 * @param ProductVo pageQuery
	 * @return
	 * @author: liang shun wang
	 * @throws Exception
	 * @date: 2013-5-22 下午15:10:03
	 */
	@RequestMapping("getAjaxSupplierInfoList")
	@ResponseBody
	public String getAjaxSupplierInfoList(SupplierVo productVo, PageQuery pageQuery) throws Exception {
		// PageFinder<ProductVo1> productVoList =
		// this.productService.getPagedProductListByProduct(productVo,
		// pageQuery);
		PageFinder<SupplierInfo> productVoList = this.supplierInfoService.querySupplier(productVo, pageQuery);
		ModelMap map = new ModelMap();
		map.put("Rows", productVoList.getData());
		map.put("Total", productVoList.getRowCount());
		return JsonHelper2.toJson(map);
	}

	/*
	 * public String ajaxPageFinderSupplier(SupplierInfo supplierInfo, PageQuery
	 * pageQuery, ModelMap map) { JSONObject jsonObj = new JSONObject();
	 * PageFinder<SupplierInfo> pageFinder =
	 * this.supplierInfoService.querySupplierInfos(supplierInfo, pageQuery);
	 * jsonObj.put("Rows", pageFinder.getData()); //ss
	 * map.put("supplierInfoList", supplierInfo); jsonObj.put("Total",
	 * pageFinder.getRowCount()); return jsonObj.toJSONString(); }
	 */
}